/**
 * @(#)com.framework.web.restful.controller.AppInterfaceController
 *
 * Copyright (c) 2014-2018 上海纬视瑞科技有限公司
 *
 * DESC:
 *
 */
package com.framework.web.restful.controller;

import com.framework.core.annotation.SpringContextHolder;
import com.framework.web.restful.common.AppErrorCode;
import com.framework.web.restful.doamin.*;
import com.framework.web.restful.util.MessageUtil;
import com.framework.web.restful.util.RestfulMethodMappingReader;
import com.framework.web.restful.util.RestfulUtil;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * APP 统一的入口
 * @author fusf
 * @version 1.0  2016/9/1
 */
@RestController
public class AppInterfaceController implements AppErrorCode{

    private static final Logger logger = Logger.getLogger(AppInterfaceController.class);


    /**
     * API统一入口处理服务
     *
     * @param requestInfo
     * @param request
     * @param response
     * @return 处理结果
     */
    @RequestMapping(method = RequestMethod.POST, value = "/platform/appServiceCall",
            produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object procService(
            @RequestBody AlarmAppServiceRequestInfo requestInfo,HttpServletRequest request, HttpServletResponse response) {
        Object returnObj = null;
        logger.info("发现API请求，procService服务开始执行");
        // JSON-RPC的method属性获取
        String requestMethod = requestInfo.getMethod();
        // JSON-RPC的id属性获取
        int id = requestInfo.getId();
        logger.info("Client ip:" + request.getRemoteHost()
                + ", method name:" + requestMethod
                + ", 请求匹配Id:" + id);
        // JSON-RPC标准格式check
        if (!RestfulUtil.checkJsonRpcFormat(requestInfo)) {
            returnObj = MessageUtil.createMsg(E50000000);
        } else {
            //获取用户账号状态
            returnObj = getLoginObj(requestInfo);
        }

        if (returnObj == null) {
            returnObj = dispatch(requestInfo);
        }
        //错误message设置
        if (returnObj instanceof MessageDomain) {
            MessageDomain apiMessage = (MessageDomain) returnObj;
            MessageReader errorReader = new MessageReader(request);
            CAError caError = new CAError();
            caError.setCode(apiMessage.getCode());
            caError.setMessage(errorReader.getMsg(apiMessage));
            return RestfulUtil.setCommonErrorRusltObj(id, caError);
        }

        //日志设置
        //setLog(request, requestInfo, returnObj);
        return returnObj;
    }

    /**
     * 转发给各个service做处理
     *
     * @param requestInfo
     * @return
     */
    private Object dispatch(AlarmAppServiceRequestInfo requestInfo) {
        Object returnObj = null;
        // JSON-RPC的method属性获取
        String requestMethod = requestInfo.getMethod();
        //判断请求的执行方法是否在Mapper中存在。
        CaseInsensitiveMap methodMapping = RestfulUtil.getMethodMapping(
                RestfulMethodMappingReader.APP_ALARM);
        if (methodMapping == null) {
            logger.info("获取MethodMapping失败！");
        }
        APIMethodBean procMethod = (APIMethodBean) methodMapping.get(requestMethod);

        if (procMethod == null) {
            //没有找到请求的执行方法
            String[] args = {requestMethod};
            return MessageUtil.createMsg(E50000001, args);
        }
        //dispatch转发给具体方法(procMethod)执行处理
        //beanId
        String beanId = procMethod.getBeanId();
        //method
        String method = procMethod.getMethod();
        Object beanClass = SpringContextHolder.getBean(beanId);
        Method m;
        try {
            m = beanClass.getClass().getMethod(method, AlarmAppServiceRequestInfo.class);
            //提高性能
            m.setAccessible(true);
            returnObj = m.invoke(beanClass, requestInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return MessageUtil.createMsg(E50000002);
        }

        return returnObj;
    }


    /**
     * 获取用户登录信息
     *
     * @return
     */
    private Object getLoginObj(AlarmAppServiceRequestInfo requestInfo) {
        Object returnObj = null;
        // JSON-RPC的method属性获取
        String requestMethod = requestInfo.getMethod();
        // JSON-RPC的id属性获取
        int id = requestInfo.getId();
        // JSON-RPC的params属性获取
        AlarmAppServiceRequestParam params = requestInfo.getParams();
        //请求中含有用户GUID的情况下，先判断是否用户已登录或者合法
        if (params != null && params.getUserGuid() != null
                && !StringUtils.EMPTY.equals(params.getUserGuid())) {
            //请求信息中含有用户信息
            logger.info("请求信息中含有用户uid：userGuid：" + params.getUserGuid());
            Object alreadyLoginObj = null;
                   /* = authorizationApiService.checkAlreadyLogin(
                    params.getUserGuid(),
                    id);*/
            if ("APP_ACTION_LOGIN".equals(requestMethod.toUpperCase())) {
                // 用户已登录，清除application 返回error：
                if (alreadyLoginObj == null) {
                    returnObj = MessageUtil.createMsg(E50010000);
                }
            } else {
                // 非用户登录的情况下，判断用户是否登录。
                if (alreadyLoginObj != null) {
                    //存在过期或者不合法
                    returnObj = alreadyLoginObj;
                }
            }
        } else {//目前代理服务器只是登录，没有其他操作
            if (!("APP_ACTION_LOGIN".equals(requestMethod.toUpperCase()) || "CA_ACTION_LOGIN".equals(requestMethod.toUpperCase()) || "ME_ACTION_LOGIN".equals(requestMethod.toUpperCase()))) {
                logger.info("用户账号已失效！");
                return MessageUtil.createMsg(E50010007);
            }
        }
        return returnObj;
    }



    /**
     * app端记录日志
     *
     * @param request
     * @param requestInfo
     * @param returnObj
     */
  /*  private void setLog(HttpServletRequest request, AlarmAppServiceRequestInfo requestInfo, Object returnObj) {
        // servletContext获取
        ServletContext application = request.getSession().getServletContext();
        // requestMethod
        String requestMethod = requestInfo.getMethod().toUpperCase();
        // userGuid
        String userGuid = null;
        if ("MS_ACTION_LOGIN".equals(requestMethod)) {
            //login
            if (returnObj instanceof RestFulResultVo) {
                RestFulResultVo<ApiActionLogin> loginRet = new RestFulResultVo<ApiActionLogin>();
                BeanUtils.copyProperties(returnObj, loginRet);
                ApiActionLogin result = loginRet.getResult();
                userGuid = result.getUserGuid();
            }
        } else {
            userGuid = requestInfo.getParams().getUserGuid();
        }
        if (userGuid != null) {
            ApiSessionVo svo = (ApiSessionVo) application.getAttribute(userGuid);
            if (svo == null) return;
            *//*Employee user = employeeService.findById(svo.getEmpId());
            String ip = RestfulUtil.getIpAddr(request);
            UserThread userThread = new UserThread(user, ip, requestMethod, svo.getDevice(), userActionLogService,
                    basicDataService);
            userThread.start();*//*
        }
    }*/


}
